package cn.kz.keepass_android;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.kz.keepass_android.util.Constant;
import cn.kz.keepass_android.util.Encrypt;
import cn.kz.keepass_android.util.HttpUtil;
import cn.kz.keepass_android.util.KeepassUtil;
import cn.kz.keepass_android.util.SPUtil;
import de.slackspace.openkeepass.domain.Entry;
import de.slackspace.openkeepass.domain.KeePassFile;

/**
 * Created by kz on 2017/3/3.
 */
public class KeepassActivity extends AppCompatActivity implements DialogListener {
    private RecyclerView mRecyclerView;
    private AlertDialog dialog;
    private String password;
    private String dbPath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.pass_list);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        dbPath = SPUtil.getString(KeepassActivity.this, Constant.DB_PATH);
        password = SPUtil.getString(KeepassActivity.this, Constant.PASSWORD);

        if (dbPath != null && password != null) {
            System.out.println("main");
            searchAndShow();
        }

        if (dbPath == null) {
            Intent intent = new Intent(KeepassActivity.this, SettingActivity.class);
            startActivity(intent);
        }

        if (password == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(KeepassActivity.this);

            builder.setView(R.layout.pwd_dialog);
            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Toast.makeText(KeepassActivity.this, "ok", Toast.LENGTH_SHORT).show();
                    KeepassActivity.this.onPositiveButtonClicked();
                }
            });
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Toast.makeText(getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show();
                    KeepassActivity.this.onPositiveButtonClicked();
                }
            });
            dialog = builder.create();
            dialog.show();
        }

    }

    private void searchAndShow() {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        String result = extras.getString(Constant.QRCODE_RESULT);

        dbPath = dbPath == null ? SPUtil.getString(KeepassActivity.this, Constant.DB_PATH) : dbPath;
        password = password == null ? SPUtil.getString(KeepassActivity.this, Constant.PASSWORD) : password;

        List<Entry> entries = null;
        String id = null;
        String type = null;
        String key = null;
        try {

            KeePassFile db = KeepassUtil.getDB(dbPath, password);

            JSONObject jsonObject = JSONObject.parseObject(result);
            key = jsonObject.getString(Constant.KEY);
            id = jsonObject.getString(Constant.ID);
            String href = jsonObject.getString(Constant.HREF);
            type = jsonObject.getString(Constant.TYPE);

            entries = KeepassUtil.search(db, href);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        final MyAdapter adapter = new MyAdapter(entries);

        mRecyclerView.setAdapter(adapter);

        final String finalId = id;
        final String finalKey = key;
        final String finalType = type;
        adapter.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Entry entry = adapter.get(mRecyclerView.getChildLayoutPosition(view));
                Map<String, String> map = new HashMap<>();
                map.put("username", entry.getUsername());
                map.put("password", entry.getPassword());


                String encrypt = null;
                try {
                    encrypt = Encrypt.encrypt(JSON.toJSONString(map), finalKey, finalType);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                final String finalEncrypt = encrypt;
                HttpUtil.doPost(Constant.SERVER_ADDR, new HashMap<String, String>() {{
                    put("id", finalId);
                    put("content", finalEncrypt);
                }});
            }
        });
    }

    @Override
    public void onPositiveButtonClicked() {
        EditText pwd_et = (EditText) dialog.findViewById(R.id.pwd_dialog);
        if (pwd_et != null) {
            password = pwd_et.getText().toString();
            searchAndShow();
        }
    }

    @Override
    public void onNegativeButtonClicked() {

    }
}

interface DialogListener {
    void onPositiveButtonClicked();

    void onNegativeButtonClicked();
}